"""
@File: userapi.py
@Project: 约个球
@Author: zhangjian
@Time: 2022.8.23 22:30
@Description: None
"""
from functools import wraps
from flask import Blueprint, request
from flask_restful import Resource, Api
from forms.user import UserForm, LoginForm
from libs.auth import login, create_token, verify_token, api_auth
from libs.response import generate_response
from model import db
from model.user import UserManager
from libs.handler import default_error_handler
from libs.amap import geo_response

user_bp = Blueprint("userapi", __name__, url_prefix="/v1")
api = Api(user_bp)
api.handle_error = default_error_handler  # 使用异常标准化处理


class Register(Resource):
    """注册"""

    def get(self, keyword=None):
        """查询用户"""
        keyword = request.args.get("keyword")
        if keyword is not None:
            user_info = UserManager.query.filter(UserManager.username.contains(keyword)).all()
            if user_info is None:
                return generate_response(status_code=10001, message="user doesn't exist")
        else:
            user_info = UserManager.query.all()
        for user in user_info:
            user.schedules = [dict(item) for item in user.schedule]
        return generate_response(message="get user success", data=[dict(user) for user in user_info])

    def post(self):
        """新增"""
        # 通过json来接收数据
        data = request.json
        form = UserForm(data=data)
        if form.validate():
            UserManager.create_user(
                username=request.json.get("username"),
                password=request.json.get("password"),
                email=request.json.get("email"),
                sex=request.json.get("sex"),
                location_x=geo_response(request.json.get("address"))[0],
                location_y=geo_response(request.json.get("address"))[1]
            )
            return generate_response(message="add user success")
        else:
            return generate_response(message=form.errors)

    def put(self, id):
        """修改"""
        user = UserManager.query.get(id)
        if user is not None:
            data = request.json
            form = UserForm(data=data)
            if form.validate():
                UserManager.create_user(
                    username=request.json.get("username"),
                    password=request.json.get("password"),
                    email=request.json.get("email"),
                    sex=request.json.get("sex"),
                    location_x=geo_response(request.json.get("address"))[0],
                    location_y=geo_response(request.json.get("address"))[1]
                )
                return generate_response(message="update user success")
            else:
                return generate_response(message=form.errors)
        else:
            return generate_response(status_code=10001, message="user doesn't exist")

    def delete(self, id):
        """删除"""
        result = UserManager.query.get(id)
        if result is not None:
            db.session.delete(result)
            db.session.commit()
            return generate_response(message="delete user success")
        else:
            return generate_response(status_code=10001, message="user doesn't exist")


api.add_resource(Register, "/register")
api.add_resource(Register, "/register/<string:username>", endpoint="registerviewapi")
api.add_resource(Register, "/register/<int:id>", endpoint="registerviewapi2")


class LoginView(Resource):
    """登录"""

    def post(self):
        data = request.json
        form = LoginForm(data=data)
        user = form.validate()
        if user:
            # 验证通过，生成token
            token = create_token(user.id)
            return generate_response(message="login success", data={"token": token})
        else:
            return generate_response(message=form.errors)


api.add_resource(LoginView, "/login")


# 针对这一类资源（get、post、put），都需要使用装饰器
api.decorators = [login]
